package com.eml.service.dao.impl;

import com.eml.service.dao.AddressesUserDao;
import com.eml.service.entity.AddressesUser;
import com.eml.service.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class AddressUserDaoImpl implements AddressesUserDao {

    @Override
    public AddressesUser selectAddressByConsignee_Name(String consignee_name) throws Exception {
        Connection connection = JDBCUtils.getConnection ();
        String sql = "select id,address,house_number,label,consignee_name,consignee_phone from address_user where consignee_name = ?";
        PreparedStatement psmt = connection.prepareStatement (sql);
        psmt.setString (1, consignee_name);
        ResultSet rs = psmt.executeQuery ();
        while(rs.next ()){
            int id = rs.getInt ("id");
            String address = rs.getString ("address");
            String house_number = rs.getString ("house_number");
            String label = rs.getString ("label");
            String consigneeName = rs.getString ("consignee_name");
            String consignee_phone = rs.getString ("consignee_phone");
            JDBCUtils.close (connection,psmt,rs);
            return new AddressesUser (id,address,house_number,label,consigneeName,consignee_phone);
        }
        JDBCUtils.close (connection,psmt,rs);
        return null;
    }

    @Override
    public AddressesUser updateAddress(Integer id ,String address) throws Exception {
        Connection connection = JDBCUtils.getConnection ();
        String sql = "update address_user set address = ? where id=?";
        PreparedStatement psmt = connection.prepareStatement (sql);
        psmt.setString (1,address);
        psmt.setInt (2,id);
        psmt.executeUpdate ();
        JDBCUtils.close (connection, psmt);
        return null;
    }

    @Override
    public AddressesUser addAddressInsert(AddressesUser addressesUser) throws Exception {
        Connection connection = JDBCUtils.getConnection ();
        String sql = "insert into address_user (address,house_number,label,consignee_name,consignee_phone) values (?,?,?,?,?)";
        PreparedStatement psmt = connection.prepareStatement (sql);
        psmt.setString (1,addressesUser.getAddress ());
        psmt.setString (2,addressesUser.getHouse_number ());
        psmt.setString (3,addressesUser.getLabel ());
        psmt.setString (4,addressesUser.getConsignee_name ());
        psmt.setString (5,addressesUser.getConsignee_phone ());
        psmt.executeUpdate ();
        JDBCUtils.close (connection, psmt);

        return addressesUser;
    }
}
